﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.IO;

namespace DownloadBook {
    public class MergeConfigServer : UniqueInstanceBase<MergeConfigServer>{
        private string GetJsonFilePath(String hostName) {
            string configDirectory = Path.Combine(Environment.CurrentDirectory, "Symbol");
            return Path.Combine(configDirectory, hostName + ".json");
        }

        /// <summary>
        /// 加载合并章节内容配置文件
        /// </summary>
        public MergeConfig LoadConfig(String hostName) {
            MergeConfig mergeConfig = null;
            string jsonFilePath = GetJsonFilePath(hostName);
            if (File.Exists(jsonFilePath)) {
                string json = File.ReadAllText(jsonFilePath);
                mergeConfig = JsonConvert.DeserializeObject<MergeConfig>(json);
                mergeConfig.isDicty = false;
            }
            return mergeConfig;
        }

        /// <summary>
        /// 保存合并章节内容的配置文件
        /// </summary>
        public void SaveConfig(MergeConfig mergeConfig) {
            if(mergeConfig.isDicty){//如果这个配置文件确实变脏了
                string jsonFilePath = GetJsonFilePath(mergeConfig.hostName);
                string jsonDirectory = Path.GetDirectoryName(jsonFilePath);
                if (!Directory.Exists(jsonDirectory)) {
                    Directory.CreateDirectory(jsonDirectory);
                }
                string json = JsonConvert.SerializeObject(mergeConfig, Formatting.Indented);
                File.WriteAllText(jsonFilePath, json);
            }
        }

        /// <summary>
        /// 获取合并配置
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public MergeConfig GetMergeConfig(string url) {
            //先从缓存中查找
            MergeConfig mergeConfig = mergeConfig = LoadConfig(url);//文件中查找
            //检测创建新的对象
            if (mergeConfig == null) {
                mergeConfig = new MergeConfig();
                mergeConfig.hostName = HtmlUtil.GetHostName(url); ;
                mergeConfig.isDicty = false;//默认标识为非脏的对象，没设置配置时，不保存它的配置文件
            }
            return mergeConfig;
        }
    }
}
